package TypeInfo.DynamicProxyDemo;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import TypeInfo.StaticProxyDemo.*;
/**
 * Created by IntelliJ IDEA
 * author：luyanfcp
 * email：lyhxbq@gmail.com
 * time:2017/3/16
 */
public class DynamicProxyTest implements java.lang.reflect.InvocationHandler {
    //委托类
    private Object proxy;
    //委托类注入
    public DynamicProxyTest(Object proxy){
        this.proxy=proxy;
    }
    @Override
    //以下方法由生成静态对象的类调用
    public Object invoke(Object o, Method method, Object[] args) throws Throwable {
        Object result;
        /*
         * 执行调用前的操作
         * 筛选记录等工作
         */
        System.out.println(o.getClass().getName());
        System.out.println("before invoke");
        //真正执行的委托类的方法；
        //这里传入的是委托类的对象与参数；
        result=method.invoke(proxy,args);
        /*
         * 调用后的操作
         */
        System.out.println("after invoke");
        return result;
    }
    //同样我们也可以通过匿名内部类或者是lambda去实现
    private static vehicle getvehicleProxy(/*传入委托类*/vehicle vehicle){
        return (vehicle)Proxy.newProxyInstance(vehicle.class.getClassLoader(),new Class[]{vehicle.class},
                (proxy,method,args)->{
                    final Object result;
                    System.out.println("lambda表达实现");
                    result=method.invoke(vehicle,args);
                    System.out.println("over ....");
                    return result;
                });
    }
    public static void main(String[] args){
        //创建代理委托对象
        car car1=new car();
        //动态的生成代理类carProxy
        DynamicProxyTest dynamicProxyTest=new DynamicProxyTest(car1);
        vehicle carProxy=(vehicle) Proxy.newProxyInstance(dynamicProxyTest.getClass().getClassLoader()
                ,car1.getClass().getInterfaces(),dynamicProxyTest);
        carProxy.run();
        System.out.println("----------------------");
        DynamicProxyTest.getvehicleProxy(car1).run();
    }
}
